package com.yjd.merchant.api.util;

import com.yjd.comm.enums.ApiRequestWayEnum;
import com.yjd.comm.user.dto.MerchantSession;
import com.yjd.comm.util.DateUtil;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.StringUtil;
import org.apache.commons.codec.digest.DigestUtils;

/**
 * 商户access token生成工具
 * Created by yangchangyan on 2017/8/16.
 */
public class AccessTokenUtil {
    /**
     * 根据用户信息生成用户token对象
     *
     * @param merchant
     * @return
     * @throws Exception
     */
    public static String generateAccessToken(MerchantSession merchant, ApiRequestWayEnum apw) throws Exception {
        if (null == merchant) {
            FrameUtil.throwBaseException1("用户对象不能为空!");
        }

        StringBuilder tokenOriginal = new StringBuilder();
        if (ApiRequestWayEnum.WEB == apw) {
            tokenOriginal.append(merchant.getOrg_id())
            .append(merchant.getName())
            .append(merchant.getPassword())
            .append(merchant.getEncrypt())
            .append(merchant.getLast_login_ip())
            .append(merchant.getStatus());
        } else {
            tokenOriginal.append(merchant.getOrg_id())
            .append(merchant.getName())
            .append(merchant.getPassword())
            .append(merchant.getEncrypt())
            .append(DateUtil.getFristSecond(FrameUtil.getTime()))
            .append(merchant.getLast_login_ip())
            .append(merchant.getStatus())
            .append(merchant.getDevice_no())
            .append(merchant.getInuse());
        }

        return DigestUtils.md5Hex(tokenOriginal.toString());
    }

    public static void main(String[] args) {
        System.out.println();
    }
    /**
     * 验证用户的令牌是否有效
     *
     * @param merchant
     * @param token
     * @return
     * @throws Exception
     */
    public static boolean validToken(MerchantSession merchant, String token, ApiRequestWayEnum apw) throws Exception {
        if (null == merchant || StringUtil.isEmpty(token)) {
            FrameUtil.throwBaseException1("用户对象和token不能为空!");
        }
        return AccessTokenUtil.generateAccessToken(merchant, apw).equals(token);
    }
}
